let express = require('express')
const path = require('path')
const multer = require('multer')

const utils = require('../../utils')

const router = express.Router()

const storage = multer.diskStorage({
    destination(req, file, cb) {
        cb(null, path.resolve(__dirname, '../../db/files'))
    },
    filename(req, file, cb) {
        cb(null, file.originalname)
    }
})
const upload = multer({ storage })

module.exports = function() {
    router.get('/file/download', (req,res) => {
        res.download(path.resolve(__dirname, `../../db/files/${ req.query.id }`))
    })

    router.post('/file/upload', upload.single('file'), (req, res) => {
        res.send(
            utils.resultSuccess({
                fileName: req.file.filename,
                id: req.file.filename,
                fileId: req.file.filename
            })
        ).end()
    })

	return router
}
